using System;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using ctsu.BaseForms;
using ctsu.Data;

namespace ctsu.Admin.BusLogic
{

	public class SearchVisitAdmissionController : ISearchController
	{
		public event BusinessLogicEvents.BLSelectedItemEventHandler ItemSelected;
		private FormSearchBase _form;
		private SearchInfo _si;

		public SearchVisitAdmissionController(FormSearchBase form, SearchInfo si)
		{
			this._form = form;  //the search form
			this._si = si;
		}

		#region ISearchController Members

		public void GenericAction(object sender, EventArgs e)
		{
			if (sender.ToString() == "RunInitialSearch")
			{
				RunInitialSearch();
			}
		}

		private void RunInitialSearch()
		{
			Cursor.Current = Cursors.WaitCursor;
			string sql = this._si.SqlCommand;

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);

				while (reader.Read())
				{
					ListViewItem lvi = new ListViewItem();
					int i = 0;
					string data;
					foreach (ReportColumn rc in _si.SearchResultCols)
					{
						if (reader.IsDBNull(i))
							data = "";
						else
							data = reader[rc.FieldName].ToString();
						if (i == 0)
							lvi.Text = data;
						else
							lvi.SubItems.Add(data);
						i++;
					}
					_form.SearchResults.Items.Add(lvi);
				}

				//resize the listview columns according to the results
				foreach (ColumnHeader ch in _form.SearchResults.Columns)
					ch.Width = -2;

			}
			catch
			{
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				_form.SearchResults.EndUpdate();
			}
		}

		public void RunSearch(object sender, EventArgs e)
		{

		}

		public void SearchFieldsChanged(object sender, EventArgs e)
		{
			// TODO:  Add SearchVisitAdmissionController.SearchFieldsChanged implementation
		}

		#endregion

		#region IFormClose Members

		public void Cancel(object sender, EventArgs e)
		{
			// TODO:  Add SearchVisitAdmissionController.Cancel implementation
		}

		public void Accept(object sender, EventArgs e)
		{
			// TODO:  Add SearchVisitAdmissionController.Accept implementation
		}

		public void Closing(object sender, CancelEventArgs e)
		{
			// TODO:  Add SearchVisitAdmissionController.Closing implementation
		}

		public void Exit(object sender, EventArgs e)
		{
			// TODO:  Add SearchVisitAdmissionController.Exit implementation
		}

		#endregion
	}
}
